package engine

import (
	"net/http"
	"sync/atomic"
)

// Backend 表示后端服务器
type Backend struct {
	URL       string
	Weight    int
	Health    atomic.Bool
	FailCount atomic.Int64
}

func (b *Backend) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// 实现代理转发逻辑
	forwarder := NewHTTPForwarder(&DirectForwarder{backend: b.URL})
	forwarder.ServeHTTP(w, r)
}

// RequestForwarder 定义请求转发接口
type RequestForwarder interface {
	Forward(req *http.Request) (*http.Response, error)
	Close() error
}

// DirectForwarder 直接转发实现
type DirectForwarder struct {
	backend string
	client  *http.Client
}

func (f *DirectForwarder) Forward(req *http.Request) (*http.Response, error) {
	if f.client == nil {
		f.client = &http.Client{}
	}
	proxyReq, err := http.NewRequest(req.Method, f.backend+req.URL.Path, req.Body)
	if err != nil {
		return nil, err
	}
	proxyReq.Header = req.Header
	return f.client.Do(proxyReq)
}

func (f *DirectForwarder) Close() error {
	return nil
}
